﻿using System.ServiceModel;
using System.ServiceModel.Description;
using CoreEx.Common.Extensions;
using LinFu.IoC;
using LinFu.IoC.Configuration;

namespace CoreEx.ServiceModel.Implementation
{
    /// <summary>
    /// Initializes a <see cref="ServiceDescription"/> by adding all registered <see cref="IServiceBehavior"/>
    /// implementations and then initializes all service endpoints from the target service.
    /// </summary>  
    [Implements(typeof(IInitializer<ServiceHost>), ServiceName = "ServiceInitializer")]
    public class ServiceInitializer : InitializerBase<ServiceHost>
    {
        /// <summary>
        /// Adds all registered <see cref="IServiceBehavior"/> implementations to 
        /// the <see cref="ServiceEndpoint.Behaviors"/> collection.
        /// </summary>
        /// <param name="serviceHost">The <see cref="ServiceHost"/> currently being  initialized.</param>
        public override void Initialize(ServiceHost serviceHost)
        {            
            
            var registeredServiceBehaviors = ServiceContainer.GetServices<IServiceBehavior>();
            registeredServiceBehaviors.ForEach(eb => serviceHost.Description.Behaviors.Add(eb));

            serviceHost.Description.Endpoints.ForEach(InitializeServiceEndpoint);
        }

        private void InitializeServiceEndpoint(ServiceEndpoint serviceEndpoint)
        {
            var serviceEndpointInitializers = ServiceContainer.GetServices<IInitializer<ServiceEndpoint>>();
            serviceEndpointInitializers.ForEach(oi => oi.Initialize(serviceEndpoint));
        }

    }
}
